package cn.hfjava.kz.service.impl;

import cn.hfjava.kz.entity.po.RolePerm;
import cn.hfjava.kz.entity.po.User;
import cn.hfjava.kz.service.PermissionService;
import cn.hfjava.kz.service.RolePermService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hfjava.kz.entity.po.Role;
import cn.hfjava.kz.service.RoleService;
import cn.hfjava.kz.mapper.RoleMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author lds
* @description 针对表【roles(角色表)】的数据库操作Service实现
* @createDate 2024-07-16 11:46:02
*/
@RequiredArgsConstructor
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{
    private final RoleMapper roleMapper;
    private final RolePermService rolePermissionService;

    @Override
    public List<User> isExistsByRoleId(Integer id) {
        return this.baseMapper.isExistsByRoleId(id);
    }

    /**
     * 根据角色ID获得角色信息
     *
     * @param roleId 角色Id
     * @return
     */
    @Override
    public Role findRoleById(Integer roleId) {

        // 创建临时集合，用于封装当前角色的权限ID集合
        List<Integer> permIds = Lists.newArrayList();
        Role roleObj = this.getById(roleId);
        if (roleObj != null) {
            // 根据角色id从角色权限表中获取角色权限信息集合
            LambdaQueryWrapper<RolePerm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(RolePerm::getRoleId, roleId);
            List<RolePerm> rolePermList = rolePermissionService.list(wrapper);
            //根据权限ID查询权限信息列表
            // 根据权限id从权限表中获取权限名称
            rolePermList.forEach(p->{
                //Permission permission = permissionService.getById(p.getPermId());
                //permList.add(permission);
                permIds.add(p.getPermId());
            });
            roleObj.setPermIds(permIds);
        }
        return roleObj;
    }

    @Override
    public List<Role> findRoleList() {
        return roleMapper.findRoleList();
    }
}
